﻿/**
 * 从本地数据库查找软件地址
 */
import rep from "./reptile"
import htt from "./htt"
import color from "./color";
import sugar from "./sugar"
import systemType from "./systemType"
import path from 'path'

const URL = "http://127.0.0.1:926/getConfig?name=";
//"http://106.55.162.218:926/getConfig?name="

let headers:any = {
    "sec-ch-ua-platform": "Windows",
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36 Edg/93.0.961.44"
}
let http = require("http")
// 兼容性
let compatible = {
    "windows":[
        "windows11",
        "windows10",
        "windows8",
        "windows7",
        "windowsvista",
        "windowsxp",
        "windows2000",
    ],
    "mac":["mac"],
    "linux":["linux"],
}

export default function lookup (name:string){
    return new Promise(response=>{
        http.get(URL+name,(res)=>{
            let value = "";
            res.on("data",a=>value+=a)
            res.on("end",_=>{
                if(value==="null"){
                    // 找不到软件配置，直接回调
                    response(undefined)
                }else{
                    let i = JSON.parse(value);
                    let {data,share} = pars(i);
                    if(!data){
                        console.log("不支持此系统版本")
                        return
                    } 
                    // 系统级别的共享 < 版本级别的共享 < 系统位数级别的共享 < 自身
                    data.url  || (data.url  = share.url || i.url);
                    data.type || (data.type = share.type || i.type);
                    data.regular || (data.regular = share.regular || {});
                    data.regular?.merge || (data.regular.merge = share.merge);
                    type(data,share,i).then(e=>response({url:e,headers:i.headers}));
                }
            })
        })
    })
}


// 根据系统配置信息选择配置
function pars (data:any,type?:any,index?:any){
    if(!type){
        // 获取系统信息
        type = systemType();
        index = Number(compatible[type.system].indexOf(type.edition))+1
    }
    let target = undefined;
    if(data.system?.[type.system]?.[type.edition] != undefined){
        target = data.system[type.system][type.edition];
    }else if(index < (compatible[type.system].length-1)){
        // 有下一个版本 index对应着下一个版本
        type.edition = compatible[type.system][index];
        return pars(data,type,++index)
    }else if(Object.keys(compatible[type.system]).some((e:string)=>Object.keys(data.system?.[type.system] || {}).some((ee:string)=>e===ee))){
        // 这个软件不支持
        return "没有此系统支持的版本";
    }else if(data.system?.[type.system]){
            target = data.system?.[type.system];
    }else if(type.system === "windows" && !Object.keys(compatible).some(e=>Object.keys(data.system || {}).some(ee=>e===ee))){
            target = data.system || data;
    }else{
        return "没有此系统支持的版本";
    }


    let reg_mer = (e)=>{
        if(e.regular || e.merge)
            return {regular:e.regular,merge:e.merge}
    }

    let sha = ()=>{
        if(data.system?.[type.system]?.[type.edition]?.public){
            return data.system[type.system][type.edition].public;
        }else if( data.system?.[type.system]?.[type.edition]?.regular ){
            return reg_mer(data.system[type.system][type.edition])
        }
        if(data.system?.[type.system]?.public){
            return data.system[type.system].public;
        }else if(data.system?.[type.system]?.[type.edition]?.regular){
            return reg_mer(data.system[type.system][type.edition].regular);
        }

        if(data.system?.public){
            return data.system?.public
        }else if(data.system?.regular){
            return reg_mer(data.system.regular)
        }

        if(data.public){
            return data.public
        }else if(data.regular){
            return reg_mer(data)
        }

        return {};
    }

    // 走到这里就是需要选择 系统位数了
    let share = sha();

    switch (type.digit){
        case "64":{
            if(target["64"]){
                return {
                    share,
                    data:target["64"]
                }
            }
        }
        case "32":{
            if(target["32"]){
                return {
                    share,
                    data:target["32"]
                }
            }
        }
        default :{
            //不分 32 64 说明是通用的
            return {
                share,
                data:target
            }
        }
    }
}


// 根据类型执行操作
function type(web:any,share:any,startingPoint:any){
    return new Promise(async response=>{
        if(!web.type || web.type === "data"){
            // 这个下载地址是不变的，不需要爬取
            response(web.url)
            return true
        }else if(web.type === "html"){
            html(web,share,startingPoint).then(e=>response(e))
            return true
        }else if(web.type === "json"){
            get(web.url,web.headers?web.headers:headers).then(e=>{
                web.json.forEach((ee:any)=>{e = e[ee]})
                response(e)
            })
        }else if(web.type === "custom"){
            // 这个处理太复杂，启动自定义处理
            response(await (require(path.join(__dirname,"\\..\\"+web.custon)))(web))
        }
    })
}


// 类型为html的处理方法
function html(web:any,share:any,startingPoint:any){
    return new Promise((ress:Function)=>{
        // 需要爬取下载地址
        rep(web.url,web.headers || headers,web,startingPoint).then((address:string)=>{
            if(!address){ console.log("地址爬取失败,请更新正则"); return}
            // 看下这个东西是否有需要合并的
      
            if(web.regular.merge){
                let merge = sugar(web.regular.merge,address,startingPoint);
                // str就是需要合并的数据
                if(/{[ ]*this[ ]*}/.test(web.regular.merge)){
                    address = merge;
                }else{
                    address = merge+address;
                }
            }else{
                // 没有合并项，默认向下合并
                address = web.next?.url ? web.next.url+address : address;
            }
            
            console.log("获取成功>>>",color("绿色",address))

            if(web.next){
                console.log("进一步获取");
                web.next.regular || (web.next.regular = web.regular)
                let next = {
                    ...web.next,
                    url     :address,
                    headers :web.next.headers || web.headers,
                }

                type(next,share,startingPoint).then(e=>ress(e))
            }else{
                ress(address)
            }
        })
    })
}



// 获取json数据
function get(url:string,headers:any){
    return new Promise(ress=>{
        htt(url).get(url,{headers},res=>{
            let data = ""
            res.on("data",(a:any)=>data+=a)
            res.on("end",_=> ress(JSON.parse(data)))
        })
    })
}